Ext.onReady(function() {
	Ext.SSL_SECURE_URL = "../../ext-3.2.1/resources/images/default/s.gif";
	Ext.BLANK_IMAGE_URL = "../../ext-3.2.1/resources/images/default/s.gif";
	// Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
	Ext.util.CSS.swapStyleSheet('theme', currentTheme);
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';
	var pageSize = 20;
	
	new Ext.Viewport({
		region : 'center',
		layout : 'fit',
		items : grid
	});

	var queryButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/query.png",
		id : 'queryButton',
		cls : 'x-btn-text-icon',
		text : '查询',
		tooltip : '查询记录',
		handler : onQueryClick
	});

	var addButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/add.png",
		id : 'addButton',
		cls : 'x-btn-text-icon',
		text : '添加',
		tooltip : '添加一条新的记录',
		// disabled:true,
		handler : onAddClick
	});
	var modButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/edit.png",
		id : 'modButton',
		cls : 'x-btn-text-icon',
		text : '修改',
		// disabled:true,
		tooltip : '修改一条选中记录。',
		handler : onModClick
	});
	var delButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/del.png",
		id : 'delButton',
		cls : 'x-btn-text-icon',
		text : '删除',
		// disabled:true,
		tooltip : '删除已选中的记录。',
		handler : onDelClick
	});


	var yearArrayData = new Array();
	for (var i = 2008; i <= (new Date()).getYear() + 1; i++) {
		yearArrayData[i - 2008] = [i, i + '年'];
	}
	var yearstore = new Ext.data.SimpleStore({
		fields : [{
			name : 'value'
		}, {
			name : 'label'
		}]
	});
	yearstore.loadData(yearArrayData);
	var combo = new Ext.form.ComboBox({
		fieldLabel : '年份',
		store : yearstore,
		displayField : 'label',
		valueField : 'value',
		typeAhead : true,
		editable : false,
		mode : 'local',
		triggerAction : 'all',
		selectOnFocus : true,
		width : 100
	});
	combo.on('select', function() {
		reloadComboxWithTree();
		gridStore.proxy = new Ext.data.ScriptTagProxy({
			url : encodeURI('../../district/buildDistrict46JSONString.action?districtYear='
					+ combo.value + "&districtCode=" + comboxWithTree.value)
		});
		gridStore.reload();
	});
	if (combo.value == null)
		combo.value = curYear;
		
	var gridStore = new Ext.data.Store({
		proxy : new Ext.data.ScriptTagProxy({
			url : encodeURI('../../district/buildDistrict46JSONString.action?pid='+pid)
		}),
		reader : new Ext.data.JsonReader({
			root : 'results',
			totalProperty : 'total',
			id : 'id'
		}, [{
			name : 'code',
			mapping : 'code'
		}, {
			name : 'name',
			mapping : 'name'
		}, {
			name : 'yearStart',
			mapping : 'yearStart'
		}, {
			name : 'yearEnd',
			mapping : 'yearEnd'
		}, {
			name : 'upperId',
			mapping : 'upperId'
		}, {
			name : 'inputDate',
			mapping : 'inputDate'
		}, {
			name : 'inputMan',
			mapping : 'inputMan'
		}, {
			name : 'inputManId',
			mapping : 'inputManId'
		}]),
		remoteSort : false
	});

	var sm = new Ext.grid.CheckboxSelectionModel();

	var cm = new Ext.ux.grid.LockingColumnModel([sm, {
		id : 'code',
		header : "地区编码",
		dataIndex : 'code',
		width : 80,
		align : 'center',
		sortable : false,
		locked : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'name',
		header : "地区名称",
		dataIndex : 'name',
		width : 180,
		align : 'center',
		renderer : function(value, p, record) {
			var txt = "";
			var code = record.data.code;
			if (code.substr(2, 2) != '00')
				txt += "&nbsp;&nbsp;&nbsp;&nbsp;";
//			if (code.substr(4, 2) != '00')
//				txt += "&nbsp;&nbsp;&nbsp;&nbsp;";
//			if (code.substr(6, 2) != '00')
//				txt += "&nbsp;&nbsp;&nbsp;&nbsp;";
//			if (code.substr(8, 2) != '00')
//				txt += "&nbsp;&nbsp;&nbsp;&nbsp;";
			return txt + value;
		},
		sortable : false,
		css : 'textAlign:"left";white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'inputDate',
		header : "创建日期",
		dataIndex : 'inputDate',
		align : 'center',
		width : 120,
		sortable : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}
	]);
	
	var disName = new Ext.form.TextField({
		fieldLabel : '地区名称',
		id : 'disName',
		name : 'disName',
		width : 300,
		maxLength : 50,
		maxLengthText : "最大长度50"
	});

	// var grid = new Ext.grid.LockingGridPanel({
	var grid = new Ext.ux.grid.SSNJLOCKPAGEGrid({
		// el:'grid-div',
		id : 'grid',
		layout : 'fit',
		store : gridStore,
		loadMask : {
			msg : '正在加载数据，请稍候……'
		},
		cm : cm,
		height : gridHeight,
		sm : sm,
		viewConfig : {
			enableRowBody : false

		},
		bodyStyle : 'width:100%;',
		tbar : ['-', '地区名称：', disName, '-', queryButton, '-', addButton, '-',
				modButton, '-', delButton, '-', '&nbsp;&nbsp;&nbsp;&nbsp;'],
		frame : false,
		border : false,
		stripeRows : true
			// bbar:pagingToolbar
	});
	grid.render(Ext.get('grid-div'));
	gridStore.load({params:{start:0, limit:pageSize}});

	var formPanel;
	var win;
	function onAddClick(item) {
		var rid, code, name, upperId;
		var record, id, titleStr, codeValue,nameValue;
		titleStr = '增加记录'
		id = "";
		codeValue = "";
		nameValue = "";
		if (item == 'mod') {
			titleStr = '修改记录'
			var selectedCount = sm.getCount();
			if (selectedCount == 0) {
				Ext.Msg.alert('修改记录', '未选中任何一条记录，请选择要修改的记录！');
				return;
			} else if (selectedCount > 1) {
				Ext.Msg.alert('修改记录', '只能选择一条记录，不能同时选择多条记录！');
				return;
			}
			record = sm.getSelected();
			id = record.id;
			codeValue = record.data['code'];
			nameValue = record.data['name'];
		}

		code = new Ext.form.TextField({
			fieldLabel : '地区编码',
			id : 'code',
			name : 'district.code',
			width : 100,
			maxLength : 10,
			maxLengthText : "最大长度10",
			value : codeValue,
			allowBlank : true
		});

		upperId = new Ext.form.Hidden({
			name : 'district.upperId',
			value:pid
				// id:'districtId',
				// value:gridStore.getById(id).data['gbcode']
		});
		
		rid = new Ext.form.Hidden({
			name : 'district.id',
			value: id
				// id:'districtId',
				// value:gridStore.getById(id).data['gbcode']
		});
		
		name = new Ext.form.TextField({
			fieldLabel : '地区名称',
			id : 'name',
			name : 'district.name',
			width : 200,
			maxLength : 25,
			maxLengthText : "最大长度25",
			value : nameValue,
			allowBlank : true
		});
		if (formPanel != null) {
			formPanel.destroy(true);
			formPanel = null;
		}
		if (!formPanel) {
			formPanel = new Ext.FormPanel({
				labelAlign : 'right',
				labelWidth : 125,
				url : '../../district/save.action',
				frame : false,
				bodyStyle : 'padding:5px 5px 0',
				items : [rid, code, name, upperId]
			});
		}
		if (win != null) {
			win.destroy(true);
			win = null;
		}
		if (!win) {
			win = new Ext.Window({
				id : 'formWin',
				title : titleStr,
				border : false,
				width : 500,
				height : 150,
				minWidth : 200,
				maximizable : false,
				closeAction : 'hide',
				layout : 'fit',
				plain : false,
				closable : true,
				modal : false,
				bodyStyle : 'padding:5px;',
				buttonAlign : 'center',
				items : formPanel,
				buttons : [{
					handler : function() {
						if (formPanel.getForm().isValid()) {
							if(code.getValue()==''){
								Ext.Msg.alert('提示','请输入地区编码');
								return false;
							}
							if(name.getValue()==''){
								Ext.Msg.alert('提示','请输入地区名称');
								return false;
							}
							formPanel.getForm().submit({
								waitMsg : '正在处理，请稍等...',
								reset : true,
								failure : function(form, action) {
									Ext.MessageBox.hide();
									Ext.Msg.show({
										title : '错误',
										msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
												+ action.result.msg + '</span>',
										buttons : Ext.MessageBox.OK,
										icon : Ext.MessageBox.WARNING
									});
								},
								success : function(form, action) {
									Ext.MessageBox.hide();
									Ext.Msg.show({
										title : '成功',
										msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
												+ action.result.msg + '</span>',
										buttons : Ext.MessageBox.OK,
										icon : Ext.MessageBox.INFO
									});

									win.hide();
									gridStore.reload();
								},
								method : 'POST'
							});
						}
					},
					text : '保存'
				}, {
					handler : function() {
						win.hide();
					},
					text : '取消'
				}]
			});
		}
		win.show();
	}
	
	function onModClick(item) {
		onAddClick('mod')
	}

	function startWith(str1, str2) {
		if (str2 == null || str2 == "" || str1.length == 0
				|| str2.length > str1.length)
			return false;
		if (str1.substr(0, str2.length) == str2)
			return true;
		else
			return false;
	}

	// 停用地区
	function onStopClick(item) {
		var selectedCount = sm.getCount();
		if (selectedCount == 0) {
			Ext.Msg.alert('停用操作', '未选中要停用的地区，请选择要停用的数据！');
			return;
		} else {
			var records = sm.getSelections();
			var _ids = '';
			for (var i = 0; i < records.length; i++) {
				if (records[i].data['canDel'] == false
						&& curYear == combo.getValue()) {
					Ext.Msg.alert('停用操作', '该地区下已经设有管辖的单位不能进行停用！');
					return;
				}
			}

			Ext.Msg.confirm('停用记录', '请确定要停用该地区吗？按是将当前系统中停用该地区！', function(btn) {
				if (btn == 'yes') {
					var records = sm.getSelections();
					var _ids = '';
					for (var i = 0; i < records.length; i++) {
						_ids += records[i].id;
						// alert(records[i].data['canDel']);
						_ids += '_';
					}
					Ext.MessageBox.wait('正在处理，请稍等...');

					Ext.Ajax.request({
						url : '../../district/stopDistrict.action',
						failure : function(result, request) {
							var responseArray = Ext.util.JSON
									.decode(result.responseText);
							Ext.MessageBox.hide();
							Ext.Msg.show({
								title : '错误',
								msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
										+ action.result.msg + '</span>',
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.WARNING
							});
						},
						success : function(result, request) {
							var responseArray = Ext.util.JSON
									.decode(result.responseText);
							Ext.MessageBox.hide();
							Ext.Msg.show({
								title : '成功',
								msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
										+ responseArray.msg + '</span>',
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.INFO
							});
							gridStore.reload();
						},
						params : {
							deleteID : _ids,
							districtYear : combo.value
						}
					});
				}
			});
		}
	}
	function onDelClick(item) {
		var selectedCount = sm.getCount();
		if (selectedCount == 0) {
			Ext.Msg.alert('删除操作', '未选中要删除的数据，请选择要删除的数据！');
			return;
		} else {
			var records = sm.getSelections();
			var _ids = '';
			Ext.Msg.confirm('删除记录', '请确定要删除该地区吗？注：按是将彻底删除该地区！', function(btn) {
				if (btn == 'yes') {
					var records = sm.getSelections();
					var _ids = '';
					for (var i = 0; i < records.length; i++) {
						_ids += records[i].id;
						_ids += '_';
					}
					Ext.MessageBox.wait('正在处理，请稍等...');
					Ext.Ajax.request({
						url : '../../district/delete.action',
						failure : function(result, request) {
							var responseArray = Ext.util.JSON
									.decode(result.responseText);
							Ext.MessageBox.hide();
							Ext.Msg.show({
								title : '错误',
								msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
										+ responseArray.msg + '</span>',
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.WARNING
							});
						},
						success : function(result, request) {
							var responseArray = Ext.util.JSON
									.decode(result.responseText);
							Ext.MessageBox.hide();
							Ext.Msg.show({
								title : '成功',
								msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
										+ responseArray.msg + '</span>',
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.INFO
							});
							gridStore.reload();
						},
						params : {
							ids : _ids
						}
					});
				}
			});
		}
	}

	function onQueryClick(item) {
		gridStore.proxy = new Ext.data.ScriptTagProxy({
			url : encodeURI('../../district/buildDistrict46JSONString.action?pid='+pid+'&disName='
					+ disName.getValue())
		});
		gridStore.reload({
			params : {
				start : 0,
				limit : pageSize
			}
		});
	}
})
